package com.cathyjava.datafetcher;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import graphql.schema.DataFetcher;
import org.springframework.stereotype.Component;

import java.awt.print.Book;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author chenjing
 * @date 2021/4/27
 */
@Component
public class GraphQLDataFetchers {
    private static List<Map<String, String>> books = Arrays.asList(
            ImmutableMap.of("id", "book-1",
                    "name", "Harry Potter and the Philosopher's Stone",
                    "pageCount", "223",
                    "authorId", "author-1"),
            ImmutableMap.of("id", "book-2",
                    "name", "Moby Dick",
                    "pageCount", "635",
                    "authorId", "author-2"),
            ImmutableMap.of("id", "book-3",
                    "name", "Interview with the vampire",
                    "pageCount", "371",
                    "authorId", "author-3")
    );
    private static List<Map<String, String>> authors = Arrays.asList(
            ImmutableMap.of("id", "author-1",
                    "firstName", "Joanne",
                    "lastName", "Rowling"),
            ImmutableMap.of("id", "author-2",
                    "firstName", "Herman",
                    "lastName", "Melville"),
            ImmutableMap.of("id", "author-3",
                    "firstName", "Anne",
                    "lastName", "Rice")
    );

    public DataFetcher getAllBooks() {
        return environment -> {
            Map<String, Object> arguments = environment.getArgument("book");
            Book book = JSON.parseObject(JSON.toJSONString(arguments), Book.class);
            return books;
        };
    }

    public DataFetcher getBookById() {
        return environment -> {
            String bookId = environment.getArgument("id");
            return books.stream()
                    .filter(x -> x.get("id").equals(bookId))
                    .findFirst()
                    .orElse(null);
        };
    }

    public DataFetcher getAuthors() {
        return environment -> {
            Map<String, String> source = environment.getSource();
            String authorId = source.get("authorId");
            return authors.stream()
                    .filter(x -> x.get("id").equals(authorId))
                    .findFirst()
                    .orElse(null);
        };
    }
}